<?php

class insert_builder
{
  /*
   * My private variable
   */
  private $str_table        = '';
  private $arr_fields       = array();
  private $arr_values       = array();

  public function reset()
  {
    $this->str_table        = '';
    $this->arr_fields       = array();
    $this->arr_values       = array();
  }

  /*
   * Setters for fields
   */
  public function add_field($str_field)
  {
    if (!in_array($field, $this->arr_fields))
    {
      $this->arr_fields[] = $str_field;
    }
  }
  public function set_fields($arr_fields)
  {
    $this->arr_fields = $arr_fields;
  }

  /*
   * Setters for values
   */
  public function add_values($arr_values)
  {
    if (is_array($arr_values))
    {
      $this->arr_values[] = $arr_values;
    }
  }
  
  /*
   * @desc Устанавливает значания для вставки в таблицу.
   * 
   * @param		$arr_values - массив записей. example: array(
   *														array('id_value_1', 'field_value_11', 'field_value_21', ...),
   *														array('id_value_2', 'field_value_21', 'field_value_22', ...),
   *														...
   *													)
   * 
   */
  public function set_values($arr_values)
  {
    if (is_array($arr_values))
    {
      $this->arr_values = $arr_values;
    }
  }

  /*
   * Setter for table
   */
  public function set_table($str_tablename)
  {
    $this->str_table = $str_tablename;
  }

  private function buildInsert()
  {
    $tablename = $this->str_table;
    $fields = implode(',', $this->arr_fields);
    return "INSERT INTO $tablename ($fields) VALUES";
  }

  private function buildValues()
  {
    $inserts = array();
    foreach ($this->arr_values as $arr_values)
    {
      $inserts[] = "('" . implode("','", $arr_values)."')";
    }
    return implode(',', $inserts);
  }

  /*
   * Buildingblock caller
   */
  private function buildQuery()
  {
    $insertstring = $this->buildInsert();
    $valuestring = $this->buildValues();

    return $insertstring.' '.$valuestring.';';
  }

  /*
   * return my SQL statement
   */
  public function returnSQL()
  {
    return $this->buildQuery();
  }
}
